package com.woniuxy.flowable.task;

import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.JavaDelegate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 修改订单状态处理器
 * 在流程最终通过时调用，将订单状态更新为已通过
 */
@Slf4j
@Component
public class ModifyOrderStatusHandler implements JavaDelegate {
    
    private final RestTemplate restTemplate = new RestTemplate();
    
    @Override
    public void execute(DelegateExecution execution) {
        try {
            // 获取流程变量
            String businessKey = execution.getProcessInstanceBusinessKey();
            String currentActivityId = execution.getCurrentActivityId();
            log.info("修改订单状态，业务键：{}，当前活动：{}", businessKey, currentActivityId);
            
            if (businessKey != null) {
                // 根据当前活动确定下一步
                String nextStep = getNextStepByActivityId(currentActivityId);
                log.info("当前活动：{}，下一步：{}", currentActivityId, nextStep);
                
                if (nextStep != null) {
                    // 更新订单的当前步骤
                    String orderServiceUrl = "http://localhost:8007/api/orders/callback/update-step";
                    
                    Map<String, Object> requestBody = new HashMap<>();
                    requestBody.put("orderId", businessKey);
                    requestBody.put("currentStep", nextStep);
                    requestBody.put("processInstanceId", execution.getProcessInstanceId());
                    
                    HttpHeaders headers = new HttpHeaders();
                    headers.setContentType(MediaType.APPLICATION_JSON);
                    HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, headers);
                    
                    restTemplate.postForObject(orderServiceUrl, request, String.class);
                    
                    log.info("订单步骤更新成功，订单ID：{}，当前步骤：{}", businessKey, nextStep);
                } else {
                    // 流程完成，更新为已通过
                    String orderServiceUrl = "http://localhost:8007/api/orders/callback/approve-success";
                    
                    Map<String, Object> requestBody = new HashMap<>();
                    requestBody.put("orderId", businessKey);
                    requestBody.put("orderNo", execution.getVariable("orderNo"));
                    requestBody.put("status", "APPROVED");
                    
                    HttpHeaders headers = new HttpHeaders();
                    headers.setContentType(MediaType.APPLICATION_JSON);
                    HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, headers);
                    
                    restTemplate.postForObject(orderServiceUrl, request, String.class);
                    
                    log.info("订单审批完成，订单ID：{}", businessKey);
                }
            } else {
                log.warn("业务键为空，无法更新订单状态");
            }
            
        } catch (Exception e) {
            log.error("修改订单状态失败", e);
            throw new RuntimeException("修改订单状态失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据活动ID获取下一步
     */
    private String getNextStepByActivityId(String activityId) {
        Map<String, String> stepMap = new HashMap<>();
        stepMap.put("regionalManagerTask", "大区经理审批");
        stepMap.put("regionalDirectorTask", "市场部审批");
        stepMap.put("marketingTask", "物流总监审批");
        stepMap.put("logisticsDirectorTask", "销售总监审批");
        stepMap.put("salesDirectorTask", "公司商务审批");
        stepMap.put("companyBusinessTask", null); // 最后一步，返回null表示完成
        
        return stepMap.get(activityId);
    }
}
